/*************************************************************************
	> File Name: linklist.c
	> Author: chen
	> Mail: chen_tmacy@foxmail.com
	> Created Time: 2014年07月23日 星期三 10时12分59秒
 ************************************************************************/

#include "linklist.h"

linklist create_null_linklist(){
    linklist head;
    head = (linknode*) malloc(sizeof(linknode));
    head->next = NULL;
    return head;
}

int is_linklist_empty(linklist list){
    assert(list != NULL);
    return list->next == NULL;
}

int len_linklist(linklist list){
    int len = 0;

    while(list->next != NULL){
        list = list->next;
        len++;
    }
    return len;
}

int insert_linklist(linklist list,datatype x,int pos){
    assert(list != NULL && pos > 0);

    for(int i = pos - 1; i > 0;i--){
        list = list->next;
        if(list == NULL){
            printf(" insert position is out of bound\n");
            return 0;
        }
    }
    linknode* node = (linknode*)malloc(sizeof(linknode));
    node->data = x;

    node->next = list->next;
    list->next = node;
    return 1;
}

datatype delete_linklist(linklist list,int pos){
    assert(list != NULL|| pos > 0);

    for(int i = pos - 1;i > 0;i--){
        list = list->next;
        if(list->next == NULL){   //list指向要删除的节点的前一个节点
            printf(" delete position is out of bound\n");
            return 0;
        }
    }

    linknode* del = list->next;
    list->next = del->next;
    datatype tmp = del->data;
    free(del);
    del = NULL;
    return tmp;
}

datatype search_linklist(linklist list,int pos){
    assert(list != NULL|| pos > 0);

    for(int i = pos - 1;i > 0;i--){
        list = list->next;
        assert(list->next != NULL);   //list指向要删除的节点的前一个节点
    }
    return list->next->data;
}

